package com.wang.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.mall.bean.SysRole;
import com.wang.mall.bean.SysUserRole;
import com.wang.mall.mapper.SysRoleMapper;
import com.wang.mall.service.SysRoleMenuService;
import com.wang.mall.service.SysRoleService;
import com.wang.mall.service.SysUserRoleService;
import com.wang.mall.service.SysUserService;
import com.wang.mall.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public List<SysRole> findByUserId(Long userId) {
        return baseMapper.findByUserId(userId);
    }

    @Override
    public List<String> findRoleNameByUserId(Long userId) {
        return findByUserId(userId).stream().map(SysRole::getRoleName).collect(Collectors.toList());
    }

    /**
     * 判断当前用户是否是超级用户
     *
     * @return
     */
    public boolean isAdmin() {
        //如果不是超级管理员，则只查询自己创建的角色列表
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        List<String> roleNameByUserId = findRoleNameByUserId(userId);
        if (roleNameByUserId.contains("admin")) {
            return true;
        }
        return false;
    }

    /**
     * 判断当前用户是否是超级用户
     *
     * @return
     */
    public boolean isAdmin(Long userId) {
        //如果不是超级管理员，则只查询自己创建的角色列表
        List<String> roleNameByUserId = findRoleNameByUserId(userId);
        if (roleNameByUserId.contains("admin")) {
            return true;
        }
        return false;
    }

    @Override
    public void saveRole(SysRole role) {
        role.setCreateTime(new Date());
        this.save(role);



        //保存角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    @Transactional
    public void deleteBatch(Long[] roleIds) {
        // 查询角色是是否与用户关联
        List<SysUserRole> list = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getRoleId, roleIds));
        if (!CollectionUtils.isEmpty(list)) {
            throw new IllegalArgumentException("当前角色正在使用不能删除");
        }

        //删除角色
        this.removeByIds(Arrays.asList(roleIds));

        //删除角色与菜单关联
        sysRoleMenuService.deleteBatch(roleIds);

        //删除角色与用户关联
        sysUserRoleService.deleteBatch(roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRole role) {
        this.updateById(role);



        //更新角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    public List<Long> queryRoleIdList(Long createUserId) {
        return baseMapper.selectRoleByUserId(createUserId);
    }



    @Override
    public PageUtils queryPage(Integer page, Integer limit, String roleName) {

        //如果不是超级管理员，则只查询自己创建的角色列表
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        List<String> roleNameByUserId = findRoleNameByUserId(userId);
        if (roleNameByUserId.contains("admin")) {
            // 超级管理员 查询所有
            IPage<SysRole> page1 = page(new Page<SysRole>(page, limit), new LambdaQueryWrapper<SysRole>().eq(!StringUtils.isEmpty(roleName), SysRole::getRoleName, roleName));
            return new PageUtils(page1);
        }


        // 普通管理员 , 只能查看自己创建的用户
        IPage<SysRole> page1 = page(new Page<SysRole>(page, limit), new LambdaQueryWrapper<SysRole>()
                .eq(!StringUtils.isEmpty(roleName), SysRole::getRoleName, roleName)
                .eq(SysRole::getCreateUserId, userId));


        return new PageUtils(page1);
    }

    @Override
    public List<SysRole> select() {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

        boolean isadmin = isAdmin();
        LambdaQueryWrapper<SysRole> sysRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 如果不是超级用户只查询自己创建的
        if (!isadmin) {
            sysRoleLambdaQueryWrapper.eq(SysRole::getCreateUserId, userId);
        }


        return list(sysRoleLambdaQueryWrapper);
    }
}
